// tooltip.js
const { BrowserWindow } = require('electron');
let tooltipWindow = null;
let tooltipTimer = null;

const { createCanvas } = require('canvas');

function measureTextWidth(text, font = '13px sans-serif') {
  const canvas = createCanvas(1, 1);
  const context = canvas.getContext('2d');
  context.font = font;
  const metrics = context.measureText(text);
  return Math.ceil(metrics.width);
}

function showTooltip(x, y, text) {
  if (tooltipWindow) tooltipWindow.close();
  const width = measureTextWidth(text, '13px sans-serif') + 28
  tooltipWindow = new BrowserWindow({
    width: width,
    height: 36,
    x: parseInt((x - (width - 28) / 2)),
    y: y,
    frame: false,
    transparent: true,
    resizable: false,
    show: false,
    alwaysOnTop: true,
    focusable: false,              // 关键
    skipTaskbar: true,
    hasShadow: false,
    webPreferences: {
      sandbox: true
    }
  })
  
  tooltipWindow.setIgnoreMouseEvents(true) //

  tooltipWindow.loadURL(`data:text/html;charset=utf-8,
    <style>
      .info { 
		  margin:0; 
		  display: flex; 
		  align-items: center; 
		  justify-content: center; 
		  background:rgba(50,50,50,0.9); 
		  color:white; font-size:13px; 
		  border-radius: 4px;
		  font-family:sans-serif;
		  overflow: hidden;
		  height: 100%;
		}
    </style>
    <body style='margin:0; background:rgba(255,255,255,0);'><div class='info'>${text}</div></body>
  `);

  tooltipWindow.once('ready-to-show', () => {
    tooltipWindow.showInactive(); // 不抢焦点
  });

  tooltipTimer = setTimeout(() => {
    if (tooltipWindow) {
      tooltipWindow.close();
      tooltipWindow = null;
    }
  }, 3000);
}

function hideTooltip() {
  if (tooltipTimer) clearTimeout(tooltipTimer);
  if (tooltipWindow) {
    tooltipWindow.close();
    tooltipWindow = null;
  }
}

module.exports = { showTooltip, hideTooltip };